<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会员中心-文档管理</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome 图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <!-- 引入平台选择弹窗组件 -->
    <script src="js/platformSelectModal.js"></script>
    <!-- 引入公众号授权弹窗功能 -->
    <script src="/wechat-auth-modal.js"></script>
    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1677ff', // 主色调，类似截图中的蓝色
                        lightBg: '#f5f7fa', // 浅背景色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style>
        .content-auto {
            content-visibility: auto;
        }

        .sidebar-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: all 200ms;
        }

        .sidebar-item.active {
            background-color: #3b82f6;
            color: white;
        }

        .table-row {
            @apply hover:bg-gray-50 transition-colors;
        }

        .status-pending {
            @apply text-orange-500;
        }

        .status-published {
            @apply text-green-500;
        }

        .btn-modify {
            @apply bg-pink-500 text-white px-2 py-1 rounded text-sm hover:bg-pink-600 transition-colors;
        }

        .btn-delete {
            @apply bg-yellow-500 text-white px-2 py-1 rounded text-sm hover:bg-yellow-600 transition-colors;
        }

        .btn-publish {
            @apply bg-green-500 text-white px-2 py-1 rounded text-sm hover:bg-green-600 transition-colors;
        }

        .btn-unpublish {
            @apply bg-gray-500 text-white px-2 py-1 rounded text-sm hover:bg-gray-600 transition-colors;
        }

        .login-button {
            width: 100%;
            padding: 0.75rem;
            border-radius: 0.5rem;
            background-color: #3b82f6;
            color: white;
            font-weight: 500;
            transition: all 200ms;
        }

        .login-button:hover {
            background-color: rgba(59, 130, 246, 0.9);
        }

        .login-button:focus {
            outline: none;
            ring: 2px solid rgba(59, 130, 246, 0.5);
            ring-offset: 2px;
        }

        /* 弹窗动画类 */
        .scale-95 {
            transform: scale(0.95);
            transition: transform 0.2s ease-out;
        }

        .scale-100 {
            transform: scale(1);
            transition: transform 0.2s ease-out;
        }
    </style>
</head>

<body class="bg-lightBg min-h-screen flex">
    <!-- 侧边栏 -->
    <aside class="w-64 bg-white shadow-md">
        <div class="p-4">
            <h1 class="text-2xl font-bold text-gray-800">会员中心</h1>
            <!-- 登录按钮 -->
            <button id="showLoginModalBtn" class="login-button w-full mt-4">
                <i class="fa fa-sign-in mr-2"></i> 立即登录
            </button>
            <!-- 用户名显示 -->
            <div id="usernameDisplay" class="mt-3 text-center text-gray-600 hidden">
                <i class="fa fa-user-circle mr-1"></i>
                <span id="currentUsername"></span>
            </div>
        </div>
        <nav class="mt-4">
            <ul>
                <li>
                    <a href="index.html" class="sidebar-item">
                        <i class="fa fa-cloud-upload"></i>
                        上传文档
                    </a>
                </li>
                <!-- 文档管理 菜单项 -->
                <li>
                    <a href="documents.html" class="sidebar-item active" id="documentsLink">
                        <i class="fa fa-folder-open"></i>
                        文档管理
                    </a>
                </li>
                <!-- 新增：公众号管理 菜单项 -->
                <li>
                    <a href="wechat-accounts.html" class="sidebar-item">
                        <i class="fa fa-weixin"></i>
                        公众号管理
                    </a>
                </li>
                <!-- 新增：账号管理 菜单项 -->
                <li>
                    <a href="wechat-account-management.html" class="sidebar-item">
                        <i class="fa fa-user-circle-o"></i>
                        账号管理
                    </a>
                </li>
                <!-- 新增：抓取管理 菜单项 -->
                <li>
                    <a href="scraping.html" class="sidebar-item">
                        <i class="fa fa-scissors"></i>
                        抓取管理
                    </a>
                </li>
                <!-- 新增：数据库配置 菜单项 -->
                <li>
                    <a href="database-config.html" class="sidebar-item">
                        <i class="fa fa-database"></i>
                        数据库配置
                    </a>
                </li>
                <!-- 新增：发布管理 菜单项 -->
                <li>
                    <a href="publish-management.html" class="sidebar-item">
                        <i class="fa fa-paper-plane"></i>
                        发布管理
                    </a>
                </li>
                <li class="logout-item hidden">
                    <a href="#" class="sidebar-item" id="logoutLink">
                        <i class="fa fa-sign-out"></i>
                        退出登录
                    </a>
                </li>
            </ul>
        </nav>
    </aside>

    <!-- 主内容区 -->
    <main class="flex-1 p-8">
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-semibold text-gray-800">文档列表</h2>
                <div class="flex items-center space-x-4">
                    <div class="relative">
                        <select
                            class="bg-white border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary appearance-none pr-8">
                            <option value="all">全部</option>
                            <option value="free">免费文档</option>
                            <option value="paid">付费文档</option>
                            <option value="vip">VIP文档</option>
                        </select>
                        <i
                            class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 pointer-events-none"></i>
                    </div>
                    <div class="flex items-center space-x-2">
                        <input type="text" placeholder="请输入关键词"
                            class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary w-48">
                        <button
                            class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 transition-colors">搜索</button>
                    </div>
                </div>
            </div>

            <div class="mb-4">
                <button id="batchDeleteBtn"
                    class="bg-red-500 text-white px-4 py-2 rounded-md hover:bg-red-600 transition-colors">批量删除</button>
                <button id="batchPublishWechatBtn"
                    class="bg-green-500 text-white px-4 py-2 rounded-md hover:bg-green-600 transition-colors ml-2">批量发布到公众号</button>
                <button id="batchPublishOtherPlatformsBtn"
                    class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition-colors ml-2">批量发布到其他平台</button>
            </div>

            <!-- 文档列表表格 -->
            <div class="overflow-x-auto">
                <table class="min-w-full border-collapse">
                    <thead>
                        <tr class="bg-gray-50">
                            <th class="py-3 px-4 text-left border border-gray-200">
                                <input type="checkbox" id="selectAll">
                            </th>
                            <th class="py-3 px-4 text-left border border-gray-200">标题</th>
                            <th class="py-3 px-4 text-left border border-gray-200">用户名</th>
                            <th class="py-3 px-4 text-left border border-gray-200">分类</th>
                            <th class="py-3 px-4 text-left border border-gray-200">文档类型</th>
                            <th class="py-3 px-4 text-left border border-gray-200">文件大小</th>
                            <th class="py-3 px-4 text-left border border-gray-200">后缀</th>
                            <th class="py-3 px-4 text-left border border-gray-200">金额</th>
                            <th class="py-3 px-4 text-left border border-gray-200">状态</th>
                            <th class="py-3 px-4 text-left border border-gray-200">添加时间</th>
                            <th class="py-3 px-4 text-left border border-gray-200">操作</th>
                        </tr>
                    </thead>
                    <tbody id="documentsTableBody">
                        <!-- 文档列表内容将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页控件 -->
            <div class="mt-6 flex justify-between items-center">
                <div class="text-gray-600" id="paginationInfo">
                    显示 0-0 条，共 0 条
                </div>
                <div class="flex space-x-1" id="paginationControls">
                    <!-- 分页控件将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>
    </main>

    <!-- JavaScript 交互逻辑 -->
    <!-- 登录弹窗 -->
    <div id="loginModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md overflow-hidden transform transition-all">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-bold text-gray-800">会员登录</h2>
                    <button id="closeModalBtn" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>

                <!-- 登录错误信息 -->
                <div id="modalError" class="mb-4 bg-red-50 text-red-700 px-4 py-2 rounded-md hidden">
                    <span id="modalErrorText"></span>
                </div>

                <!-- 登录表单 -->
                <form id="loginForm">
                    <div class="mb-4">
                        <label for="modalUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                        <input type="text" id="modalUsername"
                            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                            placeholder="请输入用户名">
                    </div>

                    <div class="mb-4">
                        <label for="modalPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input type="password" id="modalPassword"
                            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                            placeholder="请输入密码">
                    </div>

                    <button type="button" id="modalLoginBtn"
                        class="w-full py-3 rounded-lg bg-primary text-white font-medium hover:bg-primary/90 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:ring-offset-2">
                        <i class="fa fa-sign-in mr-2"></i> 登录
                    </button>
                </form>

                <div class="mt-4 text-center">
                    <span class="text-gray-600">还没有账号？</span>
                    <a href="/register.html" class="text-primary hover:underline">立即注册</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // 当前页码和每页显示数量
            let currentPage = 1;
            const pageSize = 7;

            // 初始化页面
            loadDocuments();

            // 检查登录状态
            updateLoginUI();

            // 登录弹窗功能
            const loginModal = document.getElementById('loginModal');
            const showLoginModalBtn = document.getElementById('showLoginModalBtn');
            const closeLoginModalBtn = document.getElementById('closeModalBtn');
            const loginForm = document.getElementById('loginForm');
            const loginUsername = document.getElementById('modalUsername');
            const loginPassword = document.getElementById('modalPassword');
            const modalError = document.getElementById('modalError');
            const modalErrorText = document.getElementById('modalErrorText');

            // 点击登录按钮跳转到登录页面
            showLoginModalBtn.addEventListener('click', function () {
                window.location.href = '/login.html';
            });

            // 关闭登录弹窗
            closeLoginModalBtn.addEventListener('click', function () {
                loginModal.classList.add('hidden');
            });

            // 点击弹窗外区域关闭弹窗
            loginModal.addEventListener('click', function (e) {
                if (e.target === loginModal) {
                    loginModal.classList.add('hidden');
                }
            });

            // 登录表单提交
            const modalLoginBtn = document.getElementById('modalLoginBtn');
            modalLoginBtn.addEventListener('click', function () {
                const username = loginUsername.value;
                const password = loginPassword.value;

                if (!username || !password) {
                    modalErrorText.textContent = '用户名和密码不能为空';
                    modalError.classList.remove('hidden');
                    return;
                }

                // 创建URL参数
                const params = new URLSearchParams();
                params.append('username', username);
                params.append('password', password);
                params.append('rememberMe', 'off'); // 弹窗登录默认不记住密码

                // 显示加载状态
                modalLoginBtn.disabled = true;
                modalLoginBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 登录中...';
                modalError.classList.add('hidden');

                // 发送登录请求
                fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: params
                })
                    .then(response => response.json())
                    .then(data => {
                        modalLoginBtn.disabled = false;
                        modalLoginBtn.innerHTML = '<i class="fa fa-sign-in mr-2"></i> 登录';

                        if (data.code === 0) {
                            // 登录成功，存储登录状态
                            localStorage.setItem('isLoggedIn', 'true');
                            localStorage.setItem('username', username);

                            // 关闭登录弹窗
                            loginModal.classList.add('hidden');

                            // 更新登录UI
                            updateLoginUI();

                            // 显示成功提示
                            alert('登录成功！');
                        } else {
                            // 登录失败，显示错误信息
                            modalErrorText.textContent = data.message || '登录失败，请检查用户名和密码';
                            modalError.classList.remove('hidden');
                        }
                    })
                    .catch(error => {
                        console.error('登录请求失败:', error);
                        modalLoginBtn.disabled = false;
                        modalLoginBtn.innerHTML = '<i class="fa fa-sign-in mr-2"></i> 登录';
                        modalErrorText.textContent = '网络错误，请稍后再试';
                        modalError.classList.remove('hidden');
                    });
            });

            // 退出登录功能
            document.getElementById('logoutLink').addEventListener('click', function (e) {
                e.preventDefault();
                if (confirm('确定要退出登录吗？')) {
                    // 先调用服务器的退出登录接口
                    fetch('/logout', {
                        method: 'POST'
                    })
                        .then(response => response.json())
                        .catch(error => {
                            console.error('退出登录失败:', error);
                        })
                        .finally(() => {
                            // 无论服务器返回什么结果，都清除localStorage中的登录状态
                            localStorage.removeItem('isLoggedIn');
                            localStorage.removeItem('username');

                            // 更新登录UI
                            updateLoginUI();

                            // 刷新页面以确保完全退出
                            window.location.reload();
                        });
                }
            });

            // 全选/取消全选功能
            const selectAllCheckbox = $('#selectAll');
            const batchDeleteBtn = $('#batchDeleteBtn');
            const batchPublishWechatBtn = $('#batchPublishWechatBtn');
            const batchPublishOtherPlatformsBtn = $('#batchPublishOtherPlatformsBtn');

            selectAllCheckbox.on('change', function () {
                const isChecked = this.checked;
                $('.document-checkbox').each(function () {
                    this.checked = isChecked;
                });
                updateBatchButtons();
            });

            // 监听文档复选框变化
            $(document).on('change', '.document-checkbox', function () {
                updateSelectAllCheckbox();
                updateBatchButtons();
            });

            function updateSelectAllCheckbox() {
                const checkboxes = $('.document-checkbox');
                const allChecked = checkboxes.length > 0 && checkboxes.toArray().every(checkbox => checkbox.checked);
                const anyChecked = checkboxes.toArray().some(checkbox => checkbox.checked);
                selectAllCheckbox.prop('checked', allChecked);
                selectAllCheckbox.prop('indeterminate', anyChecked && !allChecked);
            }

            function updateBatchButtons() {
                const checkboxes = $('.document-checkbox');
                const anyChecked = checkboxes.toArray().some(checkbox => checkbox.checked);
                const checkedBoxes = $('.document-checkbox:checked');

                // 更新批量删除按钮
                batchDeleteBtn.prop('disabled', !anyChecked);
                if (anyChecked) {
                    batchDeleteBtn.removeClass('opacity-50 cursor-not-allowed');
                } else {
                    batchDeleteBtn.addClass('opacity-50 cursor-not-allowed');
                }

                // 更新批量发布到公众号按钮
                batchPublishWechatBtn.prop('disabled', !anyChecked);
                if (anyChecked) {
                    batchPublishWechatBtn.removeClass('opacity-50 cursor-not-allowed');
                } else {
                    batchPublishWechatBtn.addClass('opacity-50 cursor-not-allowed');
                }

                // 更新批量发布到其他平台按钮
                batchPublishOtherPlatformsBtn.prop('disabled', !anyChecked);
                if (anyChecked) {
                    batchPublishOtherPlatformsBtn.removeClass('opacity-50 cursor-not-allowed');
                } else {
                    batchPublishOtherPlatformsBtn.addClass('opacity-50 cursor-not-allowed');
                }
            }

            // 加载文档列表
            function loadDocuments() {
                // 获取筛选条件
                const searchText = $('input[placeholder="请输入关键词"]').val().trim();
                const typeFilter = $('select').val();

                // 显示加载状态
                $('#documentsTableBody').html('<tr><td colspan="11" class="py-8 text-center text-gray-500">正在加载文档...</td></tr>');

                // 发送AJAX请求获取文档数据
                $.ajax({
                    url: '/api/documents',
                    type: 'GET',
                    data: {
                        page: currentPage,
                        pageSize: pageSize,
                        search: searchText,
                        type: typeFilter
                    },
                    success: function (response) {
                        renderDocuments(response.data || []);
                        renderPagination(response.totalPages || 1, response.total || 0, response.page || 1, pageSize);
                        updateBatchButtons();
                    },
                    error: function () {
                        $('#documentsTableBody').html('<tr><td colspan="11" class="py-8 text-center text-red-500">加载文档失败，请稍后重试</td></tr>');
                    }
                });
            }

            // 格式化文件大小
            function formatFileSize(bytes) {
                if (!bytes || bytes === 0) return '0 B';
                const k = 1024;
                const sizes = ['B', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            // 将文档类型转换为中文显示
            function formatDocumentType(type) {
                const typeMap = {
                    'free': '免费',
                    'pay': '付费',
                    'vip': 'VIP'
                };
                return typeMap[type] || type;
            }

            // 计算相对时间（一分钟前、一天前、一个月前等）
            function formatRelativeTime(dateTime) {
                // 解析时间字符串为Date对象
                let date;
                if (typeof dateTime === 'string') {
                    // 尝试不同的时间格式解析
                    if (dateTime.includes('-')) {
                        // YYYY-MM-DD HH:mm:ss 格式
                        date = new Date(dateTime.replace(/\s+/, 'T'));
                    } else if (!isNaN(parseInt(dateTime))) {
                        // 时间戳格式
                        date = new Date(parseInt(dateTime));
                    } else {
                        date = new Date(dateTime);
                    }
                } else {
                    date = new Date(dateTime);
                }

                // 获取当前时间和时间差
                const now = new Date();
                const diffInSeconds = Math.floor((now - date) / 1000);

                // 计算不同时间单位的差值
                const minutes = Math.floor(diffInSeconds / 60);
                const hours = Math.floor(minutes / 60);
                const days = Math.floor(hours / 24);
                const months = Math.floor(days / 30);
                const years = Math.floor(days / 365);

                // 返回相对时间描述
                if (years > 0) {
                    return years + '年前';
                } else if (months > 0) {
                    return months + '个月前';
                } else if (days > 0) {
                    return days + '天前';
                } else if (hours > 0) {
                    return hours + '小时前';
                } else if (minutes > 0) {
                    return minutes + '分钟前';
                } else {
                    return '刚刚';
                }
            }

            // 渲染文档列表
            function renderDocuments(documents) {
                const tableBody = $('#documentsTableBody');

                if (documents.length === 0) {
                    tableBody.html('<tr><td colspan="11" class="py-8 text-center text-gray-500">暂无文档数据</td></tr>');
                    return;
                }

                let html = '';
                documents.forEach(document => {
                    const isPublished = document.status === 1;
                    html += `
                        <tr class="table-row">
                            <td class="py-3 px-4 border border-gray-200">
                                <input type="checkbox" class="document-checkbox" data-id="${document.id || ''}">
                            </td>
                            <td class="py-3 px-4 border border-gray-200">${document.title || ''}</td>
                            <td class="py-3 px-4 border border-gray-200">${document.username || ''}</td>
                            <td class="py-3 px-4 border border-gray-200">${document.category || ''}</td>
                            <td class="py-3 px-4 border border-gray-200">${formatDocumentType(document.wenType) || ''}</td>
                            <td class="py-3 px-4 border border-gray-200">${formatFileSize(document.fileSize) || '-'}</td>
                            <td class="py-3 px-4 border border-gray-200">${document.fileExt || '-'}</td>
                            <td class="py-3 px-4 border border-gray-200">${document.price || ''}</td>
                            <td class="py-3 px-4 border border-gray-200 ${isPublished ? 'status-published' : 'status-pending'}">${document.status === 1 ? '已发布' : '未发布'}</td>
                            <td class="py-3 px-4 border border-gray-200">${document.addTime ? formatRelativeTime(document.addTime) : ''}</td>
                            <td class="py-3 px-4 border border-gray-200">
                                <div class="flex space-x-1">
                                    <button class="btn-modify" data-id="${document.id || ''}">修改</button>
                                    <button class="btn-delete" data-id="${document.id || ''}">删除</button>
                                    ${!isPublished ? `
                                    <button class="btn-publish" data-id="${document.id || ''}">
                                        <i class="fa fa-check-circle"></i>
                                        发布文档
                                    </button>
                                    ` : `
                                    <button class="btn-publish-to-wechat" data-id="${document.id || ''}">
                                        <i class="fa fa-weixin" style="color: #07C160;"></i>
                                        发布到公众号
                                    </button>
                                    <button class="btn-publish-to-other-platforms" data-id="${document.id || ''}">
                                        <i class="fa fa-share-alt" style="color: #1890ff;"></i>
                                        发布到其他平台
                                    </button>
                                    `}
                                </div>
                            </td>
                        </tr>
                    `;
                });

                tableBody.html(html);
            }

            // 渲染分页控件
            function renderPagination(totalPages, totalCount, page, pageSize) {
                const paginationInfo = $('#paginationInfo');
                const paginationControls = $('#paginationControls');

                // 显示分页信息
                const startItem = (page - 1) * pageSize + 1;
                const endItem = Math.min(startItem + pageSize - 1, totalCount);
                paginationInfo.text(`显示 ${startItem}-${endItem} 条，共 ${totalCount} 条`);

                // 生成分页按钮
                let html = '';

                // 上一页按钮
                html += `
                    <button class="px-3 py-1 border border-gray-300 rounded text-gray-600 hover:bg-gray-50 disabled:opacity-50" ${page === 1 ? 'disabled' : ''} id="prevPage">
                        <i class="fa fa-chevron-left"></i>
                    </button>
                `;

                // 页码按钮
                for (let i = 1; i <= totalPages; i++) {
                    html += `
                        <button class="px-3 py-1 ${i === page ? 'bg-primary text-white' : 'border border-gray-300 text-gray-600 hover:bg-gray-50'} rounded page-btn" data-page="${i}">
                            ${i}
                        </button>
                    `;
                }

                // 下一页按钮
                html += `
                    <button class="px-3 py-1 border border-gray-300 rounded text-gray-600 hover:bg-gray-50 disabled:opacity-50" ${page === totalPages ? 'disabled' : ''} id="nextPage">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                `;

                paginationControls.html(html);

                // 移除旧的事件监听，避免重复绑定
                $('#prevPage').off('click');
                $('#nextPage').off('click');
                $('.page-btn').off('click');

                // 添加分页按钮事件监听
                $('#prevPage').on('click', function () {
                    if (currentPage > 1) {
                        currentPage = currentPage - 1;
                        loadDocuments();
                    }
                });

                $('#nextPage').on('click', function () {
                    if (currentPage < totalPages) {
                        currentPage = currentPage + 1;
                        loadDocuments();
                    }
                });

                $('.page-btn').on('click', function () {
                    currentPage = parseInt($(this).data('page'));
                    loadDocuments();
                });
            }

            // 批量删除功能
            batchDeleteBtn.on('click', function () {
                const selectedIds = $('.document-checkbox:checked')
                    .map(function () { return $(this).data('id'); })
                    .get()
                    .filter(id => id); // 过滤掉空ID

                if (selectedIds.length > 0) {
                    if (confirm(`确定要删除选中的 ${selectedIds.length} 个文档吗？`)) {
                        $.ajax({
                            url: '/api/documents/batch-delete',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(selectedIds),
                            success: function () {
                                alert(`已删除 ${selectedIds.length} 个文档`);
                                loadDocuments();
                            },
                            error: function () {
                                alert('删除文档失败，请稍后重试');
                            }
                        });
                    }
                }
            });

            // 批量发布到公众号功能
            batchPublishWechatBtn.on('click', function () {
                const selectedDocuments = $('.document-checkbox:checked').closest('tr').map(function () {
                    const row = $(this);
                    return {
                        id: row.find('.document-checkbox').data('id'),
                        title: row.find('td:nth-child(2)').text(),
                        status: row.find('td:nth-child(9)').text() === '已发布' ? 1 : 0
                    };
                }).get().filter(doc => doc.id);

                if (selectedDocuments.length === 0) {
                    alert('请选择要发布的文档');
                    return;
                }

                // 检查是否有未发布的文档
                const unpublishedDocs = selectedDocuments.filter(doc => doc.status === 0);
                if (unpublishedDocs.length > 0) {
                    if (!confirm(`选中的文档中有 ${unpublishedDocs.length} 个未发布，是否继续发布到公众号？`)) {
                        return;
                    }
                }

                // 显示批量发布确认对话框
                const docTitles = selectedDocuments.map(doc => doc.title).join('\n');
                if (confirm(`确定要将以下 ${selectedDocuments.length} 个文档发布到公众号吗？\n\n${docTitles}`)) {
                    // 存储选中的文档信息到sessionStorage
                    sessionStorage.setItem('batchDocuments', JSON.stringify(selectedDocuments));

                    // 显示公众号授权弹窗
                    if (typeof showWechatAuthModal === 'function') {
                        // 传递特殊标记表示批量发布
                        showWechatAuthModal('batch', `批量发布 ${selectedDocuments.length} 个文档`);
                    } else {
                        alert('公众号授权功能尚未加载完成，请刷新页面重试');
                    }
                }
            });

            // 批量发布到其他平台按钮点击事件
            batchPublishOtherPlatformsBtn.on('click', function () {
                const selectedDocuments = $('.document-checkbox:checked').closest('tr').map(function () {
                    const row = $(this);
                    return {
                        id: row.find('.document-checkbox').data('id'),
                        title: row.find('td:nth-child(2)').text(),
                        status: row.find('td:nth-child(9)').text() === '已发布' ? 1 : 0
                    };
                }).get().filter(doc => doc.id);

                if (selectedDocuments.length === 0) {
                    alert('请选择要发布的文档');
                    return;
                }

                // 检查是否有未发布的文档
                const unpublishedDocs = selectedDocuments.filter(doc => doc.status === 0);
                if (unpublishedDocs.length > 0) {
                    if (!confirm(`选中的文档中有 ${unpublishedDocs.length} 个未发布，是否继续发布到其他平台？`)) {
                        return;
                    }
                }

                // 显示批量发布确认对话框
                const docTitles = selectedDocuments.map(doc => doc.title).join('\n');
                if (confirm(`确定要将以下 ${selectedDocuments.length} 个文档发布到其他平台吗？\n\n${docTitles}`)) {
                    // 显示平台选择弹窗
                    platformSelectModal.showModal(selectedDocuments, true);
                }
            });

            // 修改按钮点击事件
            $(document).on('click', '.btn-modify', function () {
                const documentId = $(this).data('id');
                const documentTitle = $(this).closest('tr').find('td:nth-child(2)').text();
                alert(`正在修改文档：${documentTitle} (ID: ${documentId})`);
                // 实际项目中，这里应该跳转到修改页面或弹出修改对话框
            });

            // 删除按钮点击事件
            $(document).on('click', '.btn-delete', function () {
                const documentId = $(this).data('id');
                const documentTitle = $(this).closest('tr').find('td:nth-child(2)').text();

                if (confirm(`确定要删除文档：${documentTitle} 吗？`)) {
                    $.ajax({
                        url: `/api/documents/${documentId}`,
                        type: 'DELETE',
                        success: function () {
                            alert(`已删除文档：${documentTitle}`);
                            loadDocuments();
                        },
                        error: function () {
                            alert('删除文档失败，请稍后重试');
                        }
                    });
                }
            });

            // 发布/撤销发布按钮点击事件
            $(document).on('click', '.btn-publish, .btn-unpublish', function () {
                const documentId = $(this).data('id');
                const documentTitle = $(this).closest('tr').find('td:nth-child(2)').text();
                const isPublishButton = $(this).hasClass('btn-publish');
                const action = isPublishButton ? 'publish' : 'unpublish';
                const actionText = isPublishButton ? '发布' : '撤销发布';

                if (confirm(`确定要${actionText}文档：${documentTitle} 吗？`)) {
                    $.ajax({
                        url: `/api/documents/${documentId}/${action}`,
                        type: 'PUT',
                        success: function () {
                            alert(`已${actionText}文档：${documentTitle}`);
                            loadDocuments();
                        },
                        error: function () {
                            alert(`${actionText}文档失败，请稍后重试`);
                        }
                    });
                }
            });

            // 发布到公众号按钮点击事件
            $(document).on('click', '.btn-publish-to-wechat', function () {
                const documentId = $(this).data('id');
                const documentTitle = $(this).closest('tr').find('td:nth-child(2)').text();

                console.log('点击发布到公众号按钮:', {
                    documentId: documentId,
                    documentTitle: documentTitle,
                    buttonElement: this
                });

                // 验证documentId是否有效
                if (!documentId || documentId === '' || documentId === 'undefined') {
                    alert('无法发布文档到公众号：文档ID无效，请刷新页面后重试');
                    console.error('documentId无效:', documentId);
                    return;
                }

                // 显示公众号授权弹窗，传递文档ID和标题
                if (typeof showWechatAuthModal === 'function') {
                    showWechatAuthModal(documentId, documentTitle, 'batch');
                } else {
                    alert('公众号授权功能尚未加载完成，请刷新页面重试');
                }
            });

            // 初始化平台选择弹窗组件
            let platformSelectModal = initPlatformSelectModal();

            // 发布到别的平台按钮点击事件
            $(document).on('click', '.btn-publish-to-other-platforms', function () {
                const documentId = $(this).data('id');
                const documentTitle = $(this).closest('tr').find('td:nth-child(2)').text();
                const documentStatus = $(this).closest('tr').find('td:nth-child(9)').text() === '已发布' ? 1 : 0;

                console.log('点击发布到别的平台按钮:', {
                    documentId: documentId,
                    documentTitle: documentTitle,
                    buttonElement: this
                });

                // 验证documentId是否有效
                if (!documentId || documentId === '' || documentId === 'undefined') {
                    alert('无法发布文档到其他平台：文档ID无效，请刷新页面后重试');
                    console.error('documentId无效:', documentId);
                    return;
                }

                // 检查是否未发布
                if (documentStatus === 0) {
                    if (!confirm(`该文档尚未发布，是否继续发布到其他平台？`)) {
                        return;
                    }
                }

                // 显示平台选择弹窗
                platformSelectModal.showModal([{ id: documentId, title: documentTitle, status: documentStatus }], false);
            });

            // 搜索按钮点击事件
            $('button.bg-primary').on('click', function () {
                currentPage = 1; // 重置为第一页
                loadDocuments();
            });

            // 搜索输入框回车事件
            $('input[placeholder="请输入关键词"]').on('keypress', function (e) {
                if (e.key === 'Enter') {
                    currentPage = 1;
                    loadDocuments();
                }
            });

            // 文档类型筛选变化事件
            $('select').on('change', function () {
                currentPage = 1;
                loadDocuments();
            });
        });

        // 检查登录状态的函数
        function checkLoginStatus() {
            return new Promise((resolve) => {
                // 首先检查localStorage中的登录状态
                const localStorageLoggedIn = localStorage.getItem('isLoggedIn');
                const localStorageUsername = localStorage.getItem('username');

                if (localStorageLoggedIn === 'true' && localStorageUsername) {
                    // 即使localStorage中有登录状态，也需要向服务器验证
                    fetch('/check-login')
                        .then(response => response.json())
                        .then(data => {
                            if (data.code === 0 && data.isLoggedIn) {
                                // 服务器验证通过，确认登录状态
                                resolve({ isLoggedIn: true, username: data.username || localStorageUsername });
                            } else {
                                // 服务器验证失败，清除localStorage
                                localStorage.removeItem('isLoggedIn');
                                localStorage.removeItem('username');
                                resolve({ isLoggedIn: false, username: null });
                            }
                        })
                        .catch(error => {
                            console.error('验证登录状态失败:', error);
                            // 发生错误时，不应该信任localStorage，清除并返回未登录状态
                            localStorage.removeItem('isLoggedIn');
                            localStorage.removeItem('username');
                            resolve({ isLoggedIn: false, username: null });
                        });
                } else {
                    // localStorage中没有登录状态，返回未登录
                    resolve({ isLoggedIn: false, username: null });
                }
            });
        }

        // 根据登录状态更新界面
        async function updateLoginUI() {
            const loginButton = document.getElementById('showLoginModalBtn');
            const logoutItem = document.querySelector('.logout-item');
            const usernameDisplay = document.getElementById('usernameDisplay');
            const currentUsername = document.getElementById('currentUsername');
            if (!loginButton) return;

            const loginStatus = await checkLoginStatus();

            if (loginStatus.isLoggedIn && loginStatus.username) {
                // 已登录，隐藏登录按钮
                loginButton.style.display = 'none';

                // 显示用户名
                if (usernameDisplay && currentUsername) {
                    currentUsername.textContent = loginStatus.username;
                    usernameDisplay.classList.remove('hidden');
                }

                // 显示退出登录选项
                if (logoutItem) {
                    logoutItem.classList.remove('hidden');
                }
            } else {
                // 未登录，显示登录按钮
                loginButton.style.display = 'block';

                // 隐藏用户名显示
                if (usernameDisplay) {
                    usernameDisplay.classList.add('hidden');
                }

                // 隐藏退出登录选项
                if (logoutItem) {
                    logoutItem.classList.add('hidden');
                }
            }
        }
    </script>


</body>

</html>